// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var dialog = require("dialog");
	var constant = require("constant");
	var router = require("../hash/pageRouter");
	var databind = require("databind");
	var leftMenu = require("../leftMenu/leftMenu");
	var css_detail = require("./pickupDetail.css");
	var tools = require("tools");
	var pickupId;
	var html_oppose_pickup = require("./html_opposePickupApplication.html");
	var html_bankInfo_update = require("./html_bankInfo_update.html");
	var js_platform_main = require("./platform_main.js");
	var left;
	var html_protocol = require("./html_protocol.html");
	var init = function(page) {
		pickupId = page.params.pickupId;
		left = page.params.left || base.getUrlParam("left");
		if(left==null){
			left=9;
		}
		$(".left").removeClass("none");
		$(".table-section").removeClass("none");
		$(".footer").removeClass("none");
		$("#main").css("background", "#ffffff");
		$("#leftMenu7").find(".leftMenu-item").removeClass("leftMenu-active");
		$("#leftMenu7 .leftMenu li:first-child").addClass("leftMenu-open");
		$("#leftMenu7").find(".leftMenu-item").eq(left).addClass("leftMenu-active");
		inquirePickupApplicationDetail();
		inquireCurrentOperationList();
		initEvent();
		router.init();

	};
	var initEvent = function() {
		
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}
		
		$("#pickupDetail .ceoAudit .button-Yes").unbind("click").click(function(){
			$("#pickupDetail .supplementOpinion").attr("action", "supplementPickupCeoAuditOpinion");
			databind.submitDom($("#pickupDetail .supplementOpinion"), function() {
				base.alert(1, "保存成功");
				router.route("main/pickupDetail.html?pickupId=" + pickupId);
			});
		});
		
		$("#pickupDetail .ceoAudit .button-Submit").unbind("click").click(function(){
			$("#pickupDetail .supplementOpinion").attr("action", "submitPickupCeoAuditOpinion");
			databind.submitDom($("#pickupDetail .supplementOpinion"), function() {
				base.alert(1, "提交成功");
				router.route("main/pickupDetail.html?pickupId=" + pickupId);
			});
		});
		
		$("#pickupDetail .audit1 .button-Yes").unbind("click").click(function(){
			$("#pickupDetail .supplementOpinion").attr("action", "supplementPickupAudit1Opinion");
			databind.submitDom($("#pickupDetail .supplementOpinion"), function() {
				base.alert(1, "保存成功");
				router.route("main/pickupDetail.html?pickupId=" + pickupId);
			});
		});
		
		$("#pickupDetail .audit1 .button-Submit").unbind("click").click(function(){
			$("#pickupDetail .supplementOpinion").attr("action", "submitPickupAudit1Opinion");
			databind.submitDom($("#pickupDetail .supplementOpinion"), function() {
				base.alert(1, "提交成功");
				router.route("main/pickupDetail.html?pickupId=" + pickupId);
			});
		});
		
		$("#pickupDetail .finalAudit .button-Yes").unbind("click").click(function(){
			$("#pickupDetail .supplementOpinion").attr("action", "supplementPickupFinalAuditOpinion");
			databind.submitDom($("#pickupDetail .supplementOpinion"), function() {
				base.alert(1, "保存成功");
				router.route("main/pickupDetail.html?pickupId=" + pickupId);
			});
		});
		
		$("#pickupDetail .finalAudit .button-Submit").unbind("click").click(function(){
			$("#pickupDetail").attr("action", "submitPickupFinalAuditOpinion");
			databind.submitDom($("#pickupDetail"), function() {
				base.alert(1, "提交成功");
				router.route("main/pickupDetail.html?pickupId=" + pickupId);
			});
		});
		
		//查看审批记录
		$("#pickupDetail .auditRecord").unbind("click").click(function(){
			window.open("../auditRecord/auditRecord.html?recordType=3&recordId=" + pickupId);
		});

		//点击首页
		$(".platform_main").unbind("click").click(function() {
			top.location.href = "../main/platform_main.html";
		});
		
		//打印
		$("#pickupDetail .print").unbind("click").click(function(){
			tools.printit($("#pickupDetail"),'preview');
		});

		//点击提货审批列表
		$(".pickupList").unbind("click").click(function() {
			router.route("main/pickupList.html?left=6", true);
		});

		//拒绝提货申请
		$("#oppasePickup").on("click", function() {
			$("#popdialog").html(html_oppose_pickup);
			dialog.showDialog($("#oppose_pickup_dialog"));
			tools.inquireCommonSelectorList(9, $("#oppose_pickup_dialog .applicantReson"));
			$("#oppose_pickup_Id").val(pickupId);
			$("#opposePickupCancel").unbind("click").click(function() {
				dialog.hideDialog($("#oppose_pickup_dialog"));
			});
			$("#opposePickupSure").unbind("click").click(function() {
				databind.submitDom($("#oppose_pickup_dialog"), function() {
					base.alert(1, "拒绝提货成功！");
					dialog.hideDialog($("#oppose_pickup_dialog"));
					js_platform_main.init();
					router.route("main/pickupList.html?left=6");
				});
			});
		});

		//同意提货申请
		$("#consentPickup").on("click", function() {
			router.route("main/pickupConsent.html?pickupId=" + pickupId);
		});
		
	
	};
	
	//权限控制
    var inquireCurrentOperationList = function(){
        base.fnAjax({
            action: 'inquireCurrentOperationList.json',
            async:false,
            fnSuccess: function (data) {
                if (data.status == 200) {
                    for(var i=0;i<data.datas.length;i++){
                        var permission = data.datas[i];
                        var permissionId = permission.permissionId;
                        $.each($("#pickupDetail").find("input"), function() {
                        	var $this = $(this);
                        	if($this.attr("permissionId") == permissionId){
                        		$this.removeClass("none");
                        	}
                        });
                    }
                } else {
                    base.alert(3, data.message);
                }
            }
        });
    };
    
    //批量同步
    var syncNormalPickupExchangeContainerAll = function(){
        base.fnAjax({
            action: 'syncNormalPickupExchangeContainerAll.json',
            async:false,
            oData: {
            	pickupId: pickupId
            },
            fnSuccess: function (data) {
                if (data.status == 200) {
                	base.alert(1, "同步成功！");
                	router.route("main/pickupDetail.html?pickupId=" + pickupId);
                } else {
                    base.alert(3, data.message);
                }
            }
        });
    };

	//换货理货信息同步
	var syncNormalPickupExchangeContainer = function(containerId) {
		base.fnAjax({
			action: "syncNormalPickupExchangeContainer.json",
			oData: {
				containerId: containerId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					base.alert(1, "同步成功！");
					router.route("main/pickupDetail.html?pickupId=" + pickupId);
				} else {
				}
			}
		});
	}

	//提货申请明细
	var inquirePickupApplicationDetail = function() {
		base.fnAjax({
			action: "inquireNormalPickupApplicationDetail.json",
			oData: {
				pickupId: pickupId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					
					databind.fillForm($("#pickupDetail"), data.datas[0]);
					$("#pickupDetail .data[name=estimateAmount]").html(tools.formatCurrency($("#pickupDetail .data[name=estimateAmount]").html()));
					
					if ($("#pickupDetailDeliveryMethod").html() == 2) {
						$("#pickupDetailDeliveryMethod").html("到港");
					} else if ($("#pickupDetailDeliveryMethod").html() == 1) {
						$("#pickupDetailDeliveryMethod").html("到门");
					}

					if ($("#pickupDetailPickupMethod").html() == 1) {
						$("#pickupDetailPickupMethod").html("现金提货");
					} else if ($("#pickupDetailPickupMethod").html() == 2) {
						$("#pickupDetailPickupMethod").html("换货");
					} else {
						$("#pickupDetailPickupMethod").html("换箱");
					}

					juicer.register("getValueByKey", constant.getValueByKey);
					juicer.register("formatCurrency", tools.formatCurrency);

					var tpl1 = $("#pickupDetailBulkstockTpl").html();
					var html1 = juicer(tpl1, data);
					$("#pickupDetailBulkstockBody").html(html1);

					var tpl2 = $("#pickupDetailInventoryTpl").html();
					var html2 = juicer(tpl2, data);
					$("#pickupDetailInventoryBody").html(html2);
					
					var tpl3 = $("#exchangeBulkstockTpl").html();
					var html3 = juicer(tpl3, data);
					$("#exchangeBulkstockTable").html(html3);
					
					var tpl4 = $("#exchangeInventoryTpl").html();
					var html4 = juicer(tpl4, data);
					$("#exchangeInventoryTable").html(html4);
					
					var tpl5 = $("#exchangeBulkstockInfoTpl2").html();
					var html5 = juicer(tpl5, data);
					$("#exchangeBulkstockInfoBody2").html(html5);
					
					var fs = data.datas[0].fileUuids.split(",");
					for (var j = 0; j < fs.length; j++) {
						if ($.trim(fs[j]) != "") {
							if (tools.inquireFile(fs[j]) != "") {
								$("#pickupDetail .fs").append('<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + fs[j] + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + fs[j] + '" class="showProductIntro">' + tools.inquireFile(fs[j]) + '</a></div> ');
							}
						}
					}

					if ($("#pickupDetailInventoryBody").find("tr").length == 1) {
						$("#pickupDetailInventoryBody").parent().addClass("none");
					}
					if ($("#pickupDetailBulkstockBody").find("tr").length == 1) {
						$("#pickupDetailBulkstockBody").parent().addClass("none");
					}
					if ($("#exchangeInventoryTable").find("tr").length == 1) {
						$("#exchangeInventoryTable").parent().addClass("none");
					}
					if ($("#exchangeBulkstockTable").find("tr").length == 1) {
						$("#exchangeBulkstockTable").parent().addClass("none");
					}

					$("#pickupDetailInventoryBody").on("click", ".detail", function() {
						router.route("bulkstockTallyDetail/bulkstockTallyDetail.html?inventoryId=" + $(this).parents("tr").attr("inventoryId"));
					});
					
					//换货理货信息同步
					$(".sync").unbind("click").click(function() {
						syncNormalPickupExchangeContainer($(this).parents("tr").attr("containerId"));
					});
					
					//手动录入理货信息
					$(".manual").unbind("click").click(function() {
						var $this = $(this);
						router.route("main/fillTallyDetailInfo.html?containerId=" + $(this).parents("tr").attr("containerId") + "&pickupId=" + pickupId);
					});
					
					//手动录入理货信息
					$(".syncUpudate").unbind("click").click(function() {
						var $this = $(this);
						router.route("main/fillTallyDetailInfo.html?containerId=" + $(this).parents("tr").attr("containerId") + "&pickupId=" + pickupId);
					});
					
					//手动录入理货信息
					$(".syncDetail").unbind("click").click(function() {
						var $this = $(this);
						router.route("main/fillTallyDetailInfo.html?containerId=" + $(this).parents("tr").attr("containerId") + "&pickupId=" + pickupId + "&type=readOnly");
					});
					
					if (data.datas[0].exchangeStatus == 1) {
						$("#consentPickup").html("评估");
					} else if (data.datas[0].exchangeStatus == 2) {
						$("#oppasePickup").remove();
						$("#consentPickup").remove();
						$("#exchangeBulkstockInfoBody2").removeClass("none");
					} else if (data.datas[0].exchangeStatus == 3) {
						$("#consentPickup").html("协议上传").attr("id", "protocol");
						$("#oppasePickup").remove();
						$("#protocol").unbind("click").click(function() {
							$("#popdialog").html(html_protocol);
							dialog.showDialog($("#protocolDialog"));
							
							databind.fillForm($("#protocolDialog"), {pickupId: pickupId});
							
							$("#protocolDialog").on("change", "#protocolUuids" , function() {
								tools.uploadFile("protocolUuids", function(data) {
									var str = '<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + data.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.data[0].fileUuid + '" class="showProductIntro">' + data.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>';
									$(".protocolUuids").before(str);
									var fileUuid = [];
									for (var j = 0; j < $(".showProductIntroDiv .mas").length; j++) {
										fileUuid.push($($(".showProductIntroDiv .mas")[j]).attr("fileUuid"));
									}
									$("input[name=protocolUuids]").val(fileUuid);
								});
							});
							
							$("#protocolDialog").on("click", ".deleteProductIntro", function() {
								$(this).parent().remove();
								var fileUuid = [];
								for (var j = 0; j < $(".showProductIntroDiv .mas").length; j++) {
									fileUuid.push($($(".showProductIntroDiv .mas")[j]).attr("fileUuid"));
								}
								$("input[name=protocolUuids]").val(fileUuid);
							});
							
							$("#protocolDialog .sure").unbind("click").click(function(){
								databind.submitDom($("#protocolDialog"), function(){
									base.alert(1, "协议上传成功！");
									dialog.hideDialog($("#protocolDialog"));
									router.route("main/pickupList.html");
								});
							});
							
							$("#protocolDialog .cancel1").unbind("click").click(function(){
								dialog.hideDialog($("#protocolDialog"));
							});
						});
					}
					
					$.each($(".auditInfo .data"), function() {
						var $this = $(this);
						if ($.trim($this.html()).length == 0) {
							$this.parents(".auditInfo").remove();
						}
					});
					
					tools.barcode($("#pickupDetail .barcode"), data.datas[0].pickupNumber, "code128");
					var inventoryIds = [];
					var financeId = data.datas[0].financeId;
					var cutoffDate = data.datas[0].deliveryDate.substring(0, 10);
					var aj = 0;
					$.each(data.datas[0].containerInventorys, function() {
						aj += this.adjustment*1;
						if ($.trim(this.inventoryId) != "" && $.trim(this.inventoryId) != null) {
							inventoryIds.push(this.inventoryId);
						}
					});
					$(".bulkstockValuation").html($(".bulkstockValuation").html()*1 + aj);
					
					if (data.datas[0].pickupMethod != 1) {
						$("#pickupDetail span[name=estimateAmount]").html(0);
						$("#pickupDetail .pickupConsentSum").remove();
					}
					
					var s = data.datas[0].interestInfo.replace(new RegExp(/(＜)/g),'<');
					s = s.replace(new RegExp(/(＞)/g),'>');
					$("#pickupDetail .pickupConsentSum").html(s);
					
					
					//批量同步换货货箱信息
					$(".syncAll").unbind("click").click(function(){
						syncNormalPickupExchangeContainerAll();
					});
					
					//换箱or换货 跳过资金部 副总经理 总经理 董事长
					if (data.datas[0].pickupMethod != 1) {
						$("#pickupDetail .riskAudit").remove();
						$("#pickupDetail .riskMemberAudit").remove();
						$("#pickupDetail .audit1").remove();
						$("#pickupDetail .finalAudit").remove();
						$("#pickupDetail .audit2").remove();
					}
					
					if (data.datas[0].ceoAuditSubmitState != true) {
						$("#consentPickup").remove();
						$("#oppasePickup").remove();
					}
					
					if ($("#pickupDetail input[name=operationAuditSubmitState]").val() == "false") {
						$("#pickupDetail .audit1 .button-submit").remove();
						$("#pickupDetail .finalAudit .button-submit").remove();
					}
					
					if ($("#pickupDetail input[name=auditSubmitState1]").val() == "false") {
						$("#pickupDetail .finalAudit .button-submit").remove();
					}
					
					if (data.datas[0].applicationState == 4 || data.datas[0].applicationState == 5) {
						$("#consentPickup").remove();
						$("#oppasePickup").remove();
					}
					
					$("#pickupDetail .createBlankInfo").unbind("click").click(function(){
						$("#popdialog").html(html_bankInfo_update);
						dialog.showDialog($("#create_bankInfo_dialog"));
						
						var containerId = $(this).parents("tr").attr("containerId");
						$("#containerId").val(containerId);

						var waybillNumber = $(this).parents("tr").attr("waybillNumber");
						var caseNumber = $(this).parents("tr").attr("caseNumber");
						
						$("#create_bankInfo_dialog input[name=waybillNumber]").val(waybillNumber);
						$("#create_bankInfo_dialog input[name=caseNumber]").val(caseNumber);
						
						$("#create_bankInfo_dialog .dialogHandlerBtn").unbind("click").click(function(){
							databind.submitDom($("#create_bankInfo_dialog"), function(){
								base.alert(1, "更新成功！");
								dialog.hideDialog($("#create_bankInfo_dialog"));
								router.route("main/pickupDetail.html?pickupId="+pickupId);
							});
						});
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}

	return {
		init: init
	};
});